import os, tarfile, zipfile, rarfile, filetype#py7zr,

class ArchiveFileHelper:
        
    def __untar__(self, archivefile, targetdir):
        with tarfile.open(archivefile, 'r:*') as tar:
            tar.extractall(targetdir)
    
    def __unzip__(self, archivefile, targetdir):
        with zipfile.ZipFile(archivefile, 'r') as zip_ref:
            zip_ref.extractall(targetdir)
    
    def __un7z__(self, archivefile, targetdir):
        # with py7zr.SevenZipFile(archivefile, 'r') as z:
            # z.extractall(targetdir)
            pass
    
    def __unrar__(self, archivefile, targetdir):
        with rarfile.RarFile(archivefile) as rf:
            rf.extractall(targetdir)
        
    def compress(self, srcpath, targetdir):
        targetpath = os.path.join(targetdir, os.path.basename(srcpath) + '.zip')
        with zipfile.ZipFile(targetpath, 'w', zipfile.ZIP_DEFLATED) as zip_ref:
            for root, dirs, files in os.walk(srcpath):
                for file in files:
                    file_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_path, srcpath)
                    zip_ref.write(file_path, arcname)
        return targetpath
        
    def unCompress(self, archivefile, targetdir):
        result = filetype.guess(archivefile)
        if(result is None):
            return
        targetdir = os.path.join(targetdir, os.path.basename(archivefile))
        os.makedirs(targetdir)
        if(result.extension == 'zip'):
            self.__unzip__(archivefile, targetdir)
        elif(result.extension == '7z'):
            self.__un7z__(archivefile, targetdir)
        elif(result.extension == 'rar'):
            self.__unrar__(archivefile, targetdir)
        else:
            self.__untar__(archivefile, targetdir)